package com.example.roundimageview.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

public class RoundOne extends ImageView {
    private int bWidth = 4;// 边框宽度
    private int bColor = Color.WHITE;// 边框颜色

    private Paint mPaint;//画笔
    private int mRadius;//圆形图片的半径
    private float mScale;//图片缩放比例

    /**
     * 继承ImageView之后 会有四个构造器
     * 这里三个就够了
     * @param context
     */
    public RoundOne(Context context) {
        super(context);
    }

    public RoundOne(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundOne(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    public void setBorderWidth(int width, int color){
        bColor=color;
        bWidth=width;
    }
    /**
     * onMeasure方法
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //保持宽高相等
        int size=Math.min(getMeasuredWidth(),getMeasuredHeight());
        mRadius=size/2;
        setMeasuredDimension(size,size);
    }
    /**
     * onDraw方法
     */
    @Override
    protected void onDraw(Canvas canvas) {
//        super.onDraw(canvas);
        //边框
        int r=getMeasuredWidth()/2;
        int cx=getLeft()+r;
        int cy=getTop()+r;
        Paint borderPaint=new Paint();
        borderPaint.setColor(bColor);
        Canvas c=new Canvas();
        mPaint=new Paint();
        Drawable drawable=getDrawable();
        if (null!=drawable){
            //初始化BitmapShader,传入bitmap对象
            Bitmap bitmap=((BitmapDrawable)drawable).getBitmap();
            BitmapShader bitmapShader=new BitmapShader(bitmap,
                    Shader.TileMode.CLAMP,Shader.TileMode.CLAMP);
            //计算缩放比例
            mScale=(mRadius*2.0f)/Math.min(bitmap.getHeight(),bitmap.getWidth());
            Matrix matrix=new Matrix();
            matrix.setScale(mScale,mScale);
            bitmapShader.setLocalMatrix(matrix);
            mPaint.setShader(bitmapShader);
            //画圆形，指定号坐标，半径，画笔
            canvas.drawCircle(mRadius,mRadius,mRadius,borderPaint);
            Log.e("1", String.valueOf(mRadius-2*bWidth));
            canvas.drawCircle(mRadius,mRadius,mRadius-2*bWidth,mPaint);

        }else {
            super.onDraw(canvas);
        }

    }


}
